import pygame
from pygame.sprite import Group
from tools.settings import Settings
import game_functions as gf
from model.ship import Ship
from game_stats import Stats


def run_game():
    # 初始化游戏，并创建一个屏幕对象
    pygame.init()
    sw_setting = Settings()
    game_stats = Stats(sw_setting)
    screen = pygame.display.set_mode((sw_setting.screen_width, sw_setting.screen_height))
    pygame.display.set_caption(sw_setting.name)
    background = pygame.image.load("../images/bg_image.jpg")

    # 创建一艘飞船
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    ship_g = Group()
    ship_g.add(ship)

    # 创建外星飞船舰队
    gf.create_alien_fleet(sw_setting, screen, aliens)

    f_clock = pygame.time.Clock()
    fps = 60

    # 开始游戏主循环
    while game_stats.game_active:
        # 监视游戏事件（键盘和鼠标）
        gf.check_events(sw_setting, screen, ship, bullets)
        # 更新
        gf.update_screen(sw_setting, screen, ship, bullets, aliens, background, ship_g, game_stats)
        # 内存管理
        clean_screen_outside(bullets)
        f_clock.tick(fps)
    else:
        print("game over")


def clean_screen_outside(bullets):
    for bullet in bullets:
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)


run_game()
